package rank

import (
	"GoServer/common"
	"GoServer/entrance/platform/douyin"
	"GoServer/models"
	"GoServer/utils/config"
	"GoServer/utils/databases"
	"GoServer/utils/debug"
	"GoServer/utils/tool"
	"encoding/json"
	"fmt"
	"time"
)

func SetWorldVersion(gameName string) {
	debug.Logln(debug.Info, "设置当前世界榜单版本")

	isOnlineVersion := config.GetConfig("app").GetBool("douyin.rank_is_online_version")
	data := models.WorldVersionReuquset{
		AppId:            config.GetConfig("app").GetString("douyin.appid"),
		IsOnlineVersion:  isOnlineVersion,
		WorldRankVersion: config.GetConfig("app").GetString("douyin.world_rank_version"),
	}

	reqBody, err := json.Marshal(data)
	if err != nil {
		debug.Logln(debug.Error, "Json to Byte error :", err)
		// 请求置顶礼物失败， 返回给客户端
		return
	}
	jsonStr := string(reqBody)

	headers := map[string]string{
		"content-type": "application/json; charset=UTF-8",
		"X-Token":      douyin.GetDYAccessToken(gameName),
	}

	res, err := tool.SendPostOnceRetry(config.GetConfig("app").GetString("douyin.world_version"), jsonStr, headers)
	if err != nil {
		debug.Logln(debug.Error, err)
		// 请求置顶礼物失败， 返回给客户端
		return
	}
	msg := models.WorldVersionResponse{}
	if err := json.Unmarshal(res, &msg); err != nil {
		debug.Logln(debug.Error, err)
	}

	debug.Logln(debug.Info, "设置当前世界版本结果：", string(res))

	if msg.ErrorCode == 0 {
		debug.Logln(debug.Info, "[设置世界排行榜版本成功]")
	} else {
		debug.Logf(debug.Error, "[设置世界版本][错误code: %s][错误原因] : %s", msg.ErrorCode, msg.ErrorMessage)
	}
}

// / 同步世界榜单数据到抖音平台 （每30秒执行一次）
func SyncWorldRankToTiktok(parm interface{}) (result bool) {

	///开启同步世界榜单数据
	debug.Logln(debug.Info, "开启同步世界榜单数据")

	playerRanks, err := GetTopTenRank(databases.Rediss, int64(100))
	if err != nil {
		debug.Logln(debug.Error, "获取排行榜前十名玩家错误, error:", err)
		return true
	}

	index := 0
	var tempRankList []models.UserRankData
	for _, player := range playerRanks {
		/// 大于50分的才需要上报
		if player.Energy > 50 {
			index++
			tempRank := models.UserRankData{
				OpenId:             player.PlayerId,
				Rank:               int64(index),
				Score:              int64(player.Energy),
				WinningStreakCount: 0,
				WinningPoints:      int64(player.Energy),
			}
			tempRankList = append(tempRankList, tempRank)
		}
	}

	length := len(tempRankList)
	if length <= 0 {
		debug.Logln(debug.Info, "当前没有玩家，不需要上报世界排行榜信息：", length)
		return true
	}

	isOnlineVersion := config.GetConfig("app").GetBool("douyin.rank_is_online_version")
	data := models.WorldVersionReuquset{
		AppId:            config.GetConfig("app").GetString("douyin.appid"),
		IsOnlineVersion:  isOnlineVersion,
		WorldRankVersion: config.GetConfig("app").GetString("douyin.world_rank_version"),
		RankList:         tempRankList,
	}

	reqBody, err := json.Marshal(data)
	if err != nil {
		debug.Logln(debug.Error, "Json to Byte error :", err)
		return true
	}
	jsonStr := string(reqBody)

	headers := map[string]string{
		"content-type": "application/json",
		"X-Token":      douyin.GetDYAccessToken(common.GameName),
	}

	res, err := tool.SendPostOnceRetry(config.GetConfig("app").GetString("douyin.upload_world_rank"), jsonStr, headers)
	if err != nil {
		debug.Logln(debug.Error, err)
		return true
	}
	msg := models.WorldVersionResponse{}
	if err := json.Unmarshal(res, &msg); err != nil {
		debug.Logln(debug.Error, err)
	}

	debug.Logln(debug.Info, "更新世界榜结果数据：", string(res))

	if msg.ErrorCode == 0 {
		debug.Logln(debug.Info, "[更新世界榜排行榜版本成功]")
	} else {
		debug.Logf(debug.Error, fmt.Sprintf("[更新世界榜][错误code: %d][错误原因] : %s", msg.ErrorCode, msg.ErrorMessage))
	}

	CompleteWorldRankReport()
	return true
}

// / 完成上报
func CompleteWorldRankReport() {
	isOnlineVersion := config.GetConfig("app").GetBool("douyin.rank_is_online_version")
	data := models.WorldVersionReuquset{
		AppId:            config.GetConfig("app").GetString("douyin.appid"),
		IsOnlineVersion:  isOnlineVersion,
		WorldRankVersion: config.GetConfig("app").GetString("douyin.world_rank_version"),
		CompleteTime:     time.Now().Unix(),
	}

	reqBody, err := json.Marshal(data)
	if err != nil {
		debug.Logln(debug.Error, "Json to Byte error :", err)
		return
	}
	jsonStr := string(reqBody)

	headers := map[string]string{
		"content-type": "application/json; charset=UTF-8",
		"X-Token":      douyin.GetDYAccessToken(common.GameName),
	}

	res, err := tool.SendPostOnceRetry(config.GetConfig("app").GetString("douyin.complete_upload"), jsonStr, headers)
	if err != nil {
		debug.Logln(debug.Error, err)
		// 请求置顶礼物失败， 返回给客户端
		return
	}
	msg := models.WorldVersionResponse{}
	if err := json.Unmarshal(res, &msg); err != nil {
		debug.Logln(debug.Error, err)
	}

	debug.Logln(debug.Info, "世界榜单数据上报完成：", string(res))

	if msg.ErrorCode == 0 {
		debug.Logln(debug.Info, "[世界榜单数据上报完成]")
	} else {
		debug.Logf(debug.Error, "[世界榜单上报完成][错误code: %s][错误原因] : %s", msg.ErrorCode, msg.ErrorMessage)
		return
	}
}

// 同步游戏对局状态
func SyncGameRoundStatus(data *models.SyncGameStatusData) {
	if data.Status == 1 {
		// 每局游戏开始，清空上局玩家数据
		ClearRoundUserInfo(databases.Rediss, data.RoomId)
	}
	err := SyncGameRoundStatusInRedis(databases.Rediss, data)
	if err != nil {
		debug.Logln(debug.Error, "同步游戏回合数据到 redis 失败")
	}

	data.AppId = config.GetConfig("app").GetString("douyin.appid")
	debug.Logf(debug.Info, "开始同步游戏对局状态, 游戏状态: [%s]", data.Status)
	reqBody, err := json.Marshal(data)
	if err != nil {
		debug.Logln(debug.Error, "Json to Byte error :", err)
		return
	}
	jsonStr := string(reqBody)

	headers := map[string]string{
		"content-type": "application/json; charset=UTF-8",
		"X-Token":      douyin.GetDYAccessToken(common.GameName),
	}

	res, err := tool.SendPostOnceRetry(config.GetConfig("app").GetString("douyin.sync_game_status"), jsonStr, headers)
	if err != nil {
		debug.Logln(debug.Error, err)
		return
	}
	msg := models.WorldVersionResponse{}
	if err := json.Unmarshal(res, &msg); err != nil {
		debug.Logln(debug.Error, err)
	}

	debug.Logln(debug.Info, "游戏对局状态同步完成：", string(res))

	if msg.ErrorCode == 0 {
		debug.Logln(debug.Info, "[游戏对局状态同步成功]")
	} else {
		debug.Logf(debug.Error, fmt.Sprintf("[游戏对局状态同步][错误code: %s][错误原因] : %s", msg.ErrorCode, msg.ErrorMessage))
		return
	}
}

// 上报当前游戏数据
// / 每次上报 50 条 数据
func UploadGameRoundInfo(anchorOpenId string, roomId string, RoundId int64, userList []models.UploadUserData, complete bool) {
	debug.Logln(debug.Info, "上报当局玩家游戏数据")
	data := models.UploadUserGameData{
		AnchorOpenId: anchorOpenId,
		RoomId:       roomId,
		RoundId:      RoundId,
		AppId:        config.GetConfig("app").GetString("douyin.appid"),
		UserList:     userList,
	}

	reqBody, err := json.Marshal(data)
	if err != nil {
		debug.Logln(debug.Error, "Json to Byte error :", err)
		return
	}

	jsonStr := string(reqBody)

	headers := map[string]string{
		"content-type": "application/json; charset=UTF-8",
		"X-Token":      douyin.GetDYAccessToken(common.GameName),
	}

	res, err := tool.SendPostOnceRetry(config.GetConfig("app").GetString("douyin.upload_user_result"), jsonStr, headers)
	if err != nil {
		debug.Logln(debug.Error, err)
		// 请求置顶礼物失败， 返回给客户端
		return
	}
	msg := models.WorldVersionResponse{}
	if err := json.Unmarshal(res, &msg); err != nil {
		debug.Logln(debug.Error, err)
	}

	debug.Logln(debug.Info, "游戏对局状态同步完成：", string(res))

	if msg.ErrorCode == 0 {
		debug.Logln(debug.Info, "[游戏对局状态同步成功]")
	} else {
		debug.Logf(debug.Error, fmt.Sprintf("[游戏对局状态同步][错误code: %s][错误原因] : %s", msg.ErrorCode, msg.ErrorMessage))
		return
	}

	if complete {
		CompleteUploadUserResult(anchorOpenId, roomId, RoundId)
	}
}

func UploadGameRankList(anchorOpenId string, roomId string, RoundId int64, userList []models.UploadUserData) {
	debug.Logln(debug.Debug, "上报当局Top玩家游戏数据")
	data := models.UploadTopUserGameData{
		AnchorOpenId: anchorOpenId,
		RoomId:       roomId,
		RoundId:      RoundId,
		AppId:        config.GetConfig("app").GetString("douyin.appid"),
		RankList:     userList,
	}

	reqBody, err := json.Marshal(data)
	if err != nil {
		debug.Logln(debug.Error, "Json to Byte error :", err)
		return
	}

	jsonStr := string(reqBody)

	headers := map[string]string{
		"content-type": "application/json; charset=UTF-8",
		"X-Token":      douyin.GetDYAccessToken(common.GameName),
	}

	res, err := tool.SendPostOnceRetry(config.GetConfig("app").GetString("douyin.upload_rank_list"), jsonStr, headers)
	if err != nil {
		debug.Logln(debug.Error, err)
		return
	}
	msg := models.WorldVersionResponse{}
	if err := json.Unmarshal(res, &msg); err != nil {
		debug.Logln(debug.Error, err)
	}

	debug.Logln(debug.Info, "游戏对局当局Top状态同步完成：", string(res))

	if msg.ErrorCode == 0 {
		debug.Logln(debug.Info, "[当局Top状态同步成功]")
	} else {
		debug.Logf(debug.Error, fmt.Sprintf("[当局Top状态同步][错误code: %s][错误原因] : %s", msg.ErrorCode, msg.ErrorMessage))
		return
	}
}

// / 完成用户数据上报
func CompleteUploadUserResult(anchorOpenId string, roomId string, RoundId int64) {
	data := models.CompleteUploadUserResult{
		AnchorOpenId: anchorOpenId,
		AppId:        config.GetConfig("app").GetString("douyin.appid"),
		RoomId:       roomId,
		RoundId:      RoundId,
		CompleteTime: time.Now().Unix(),
	}

	reqBody, err := json.Marshal(data)
	if err != nil {
		debug.Logln(debug.Error, err)
		return
	}

	jsonStr := string(reqBody)

	headers := map[string]string{
		"content-type": "application/json",
		"X-Token":      douyin.GetDYAccessToken(common.GameName),
	}

	res, err := tool.SendPostOnceRetry(config.GetConfig("app").GetString("douyin.complete_upload_user_result"), jsonStr, headers)
	if err != nil {
		debug.Logln(debug.Error, err)
		return
	}
	msg := models.WorldVersionResponse{}
	if err := json.Unmarshal(res, &msg); err != nil {
		debug.Logln(debug.Error, err)
	}

	debug.Logln(debug.Info, "完成用户上报信息：", string(res))

	if msg.ErrorCode == 0 {
		debug.Logln(debug.Info, "[完成用户上报同步成功]")
	} else {
		debug.Logf(debug.Error, "[完成用户上报][错误code: %s][错误原因] : %s", msg.ErrorCode, msg.ErrorMessage)
		return
	}
}

// / 上报用户阵营数据
func UploadUserGroupInfo(GroupId string, OpenId string, RoomId string, RoundId string) {
	data := models.UploadUserGroupInfo{
		AppId:   config.GetConfig("app").GetString(".appid"),
		GroupId: GroupId,
		OpenId:  OpenId,
		RoomId:  RoomId,
		RoundId: RoundId,
	}

	reqBody, err := json.Marshal(data)
	if err != nil {
		debug.Logln(debug.Error, "Json to Byte error :", err)
		return
	}

	jsonStr := string(reqBody)

	headers := map[string]string{
		"content-type": "application/json",
		"X-Token":      douyin.GetDYAccessToken(common.GameName),
	}

	res, err := tool.SendPostOnceRetry(config.GetConfig("app").GetString("douyin.upload_user_group_info"), jsonStr, headers)
	if err != nil {
		debug.Logln(debug.Error, err)
		return
	}
	msg := models.WorldVersionResponse{}
	if err := json.Unmarshal(res, &msg); err != nil {
		debug.Logln(debug.Error, err)
	}

	debug.Logln(debug.Info, "上报用户阵营数据：", string(res))

	if msg.ErrorCode == 0 {
		debug.Logln(debug.Info, "[上报用户阵营数据同步成功]")
	} else {
		debug.Logf(debug.Error, fmt.Sprintf("[上报用户阵营][错误code: %s][错误原因] : %s", msg.ErrorCode, msg.ErrorMessage))
		return
	}
}
